package com.wowo.day4;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ArrayToStringTypeHandler implements TypeHandler<String[]> {

    // 字符串数组--> 字符串，存
    @Override
    public void setParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("in setParameter"+ Arrays.toString(parameter));
        if(parameter ==null) return;
        //String[] parameter --> "吃，喝，玩"
        String str = "";
        for(String s: parameter){
            str +=s+",";
        }
        if(str.length()>0){
            //去掉最后一个，
            str = str.substring(0,str.length()-1);
        }
        //设置参数的值
        ps.setString(i,str);
    }
    //字符串--> 数组
    @Override
    public String[] getResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getString(columnName).split(",");

    }

    @Override
    public String[] getResult(ResultSet rs, int columnIndex) throws SQLException {

        return rs.getString(columnIndex).split(",");
    }

    @Override
    public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException {

        return new String[0];
    }
}
